import {base, toast, promptBox, output, print} from 'nc-lightapp-front';

import ExportHtml from '../../../../hrpub/common/utils/exportHtml';

import PrintTable from '../../../../hrpub/common/utils/print';

import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';

let {NCSelect} = base;

let NCOption = NCSelect.NCOption;

export default class ButtonAction {
    constructor(comp) {
        this.comp = comp;
    }

    didMount = () => {
        const {props} = this.comp;
        this.buttonTool(props, true);
        this.visibleTool(true);
    };

    buttonClick = (platformProps, code) => {
        const {action, props} = this.comp;
        const {dispatch, form, exam} = props;
        const {billid} = exam;

        switch (code) {
            case 'add': //新增
                this.addButton();

                break;
            case 'batchAdd': //批量新增
                action.batAddAct.openBatchModal();
                break;
            case 'save': //保存
                this.pubSub.publish('saveItemState');
                break;
            case 'refresh': //刷新
                            // 卡片模式刷新和表格模式刷新
                exam.cardMode === true ? action.formAct.oneAction(exam.billid) : this.pubSub.publish('initData');

                break;
            case 'cancel': //取消
                this.cancelFunction(props, true);
                break;
            case 'print': //打印
                this.printDate();
                break;
            case 'out': //输出
                this.outDate();
                break;
            case 'search': //查询
                this.showSearchModal();
                break;
            case 'del': //删除
                action.table.batchDelete(exam.billid);
                break;
            case 'edit': //修改
                action.formAct.editAction();
                break;
            case 'organization':
                action.orgSta.openOrgSituationModal();
                break;
            case 'commit': //提交
                action.table.batchCommit();
                break;
            case 'recover': //收回
                action.table.batchBack();
                break;
            case 'sendMsg': //提交
                action.table.sendMsgAction();
                break;

            case 'execute': //执行
                action.table.batchImplementBefore();
                break;
            case 'psncard': //联查卡片
                this.linkSearch();
                break;
            case 'file': //附件管理
                dispatch({
                    type: 'exam/update',
                    payload: {
                        billid,
                        fileManagerModalVisible: true
                    }
                });
        }
    };

    linkSearch = async () => {
        const {props, action} = this.comp;
        const {exam, form} = props;
        if (!exam.cardMode) {
            let rows = this.comp.props.editTable.getCheckedRows('list');
            exam.nodeRefs.wpsview.openView(rows);
        } else {
            let formData = form.getAllFormValue('card').rows;
            exam.nodeRefs.wpsview.openView(formData);
        }
    }
    // 新增页面
    addButton = () => {
        const {action, props} = this.comp;
        const {dispatch, form, exam} = props;

        this.pubSub.publish('toAddPage');
    };

    /**
     * 下拉框触发事件
     * @param value 下拉框value值
     */
    handleChange = (value) => {
        const {props} = this.comp;
        const {dispatch} = props;
        dispatch({
            type: 'exam/update',
            payload: {
                probationType: value
            }
        });

        this.pubSub.publish('initData', {
            probationType: value
        });
    };

    /**
     * 打印
     */
    printDate = () => {
        const {action, props} = this.comp;
        const {dispatch, exam} = props;
        if (exam.cardMode === false) {
            this.tablePrint();
        } else {
            this.templatePrint();
        }
    };

    tablePrint = () => {
        const {action, props} = this.comp;
        const {dispatch, exam} = props;
        PrintTable(document.querySelector('.u-table'), {
            title: exam.json['gx6008-000118'], //转正办理
            maker: exam.json['gx6008-000028'],
            date: exam.json['gx6008-000029'],
            maxColLen: 18,
            beforeHtml: '',
            afterHtml: '',
            beforeAppend(tableDataList) {
                tableDataList[0].forEach((item, index) => {
                    item.shift();
                    item.splice(15);
                });
                return tableDataList;
            }
        });
    };

    // 模板打印
    templatePrint = () => {
        const {action, props} = this.comp;
        const {dispatch, exam} = props;
        // let template = this.comp.props.meta.getMeta();

        print('pdf', '/nccloud/hrtrn/regApply/RegApplyPrintAction.do', {
            appcode: exam.config.appcode,
            nodekey: exam.config.appcode,
            filename: exam.json['gx6008-000118'], //转正办理
            // oids: [template['card'].oid]
            oids: [exam.billid]
        });
    };

    /**
     * 输出
     */
    outDate = () => {
        const {action, props} = this.comp;
        const {exam, meta, editTable} = props;
        if (exam.cardMode === false) {
            this.tableOutDate();
        } else {
            this.templateOutDate();
        }
    };

    tableOutDate = () => {
        const {action, props} = this.comp;
        const {exam, meta, editTable} = props;
        const tableMeta = meta.getMeta();
        ExportHtml(
            document.querySelector('.u-table'),
            {
                //转正办理
                title: exam.json['gx6008-000118'], //转正办理
                fileName: exam.json['gx6008-000118'], //转正办理
                maker: exam.json['gx6008-000028'],
                date: exam.json['gx6008-000029']
            },
            {
                meta: tableMeta['list'],
                data: editTable.getAllRows('list'),
                showIndex: false
            }
        );
    };

    templateOutDate = () => {
        const {action, props} = this.comp;
        const {dispatch, exam} = props;
        // let template = this.comp.props.meta.getMeta();
        output({
            url: '/nccloud/hrtrn/regApply/RegApplyPrintAction.do',
            data: {
                appcode: exam.config.appcode,
                nodekey: exam.config.appcode,
                filename: exam.json['gx6008-000118'], //转正办理
                // oids: [template['card'].oid],
                oids: [exam.billid],
                outputType: 'output'
            },
            callback: () => {
            }
        });
    };

    /**
     * 人力资源组织参照
     */
    handleChangePeople = (value) => {
        const {props} = this.comp;
        const {dispatch, button, exam} = props;
        if (typeof value == 'string') {
            dispatch({
                type: 'exam/update',
                payload: {
                    refValue: {},
                    widget: true
                }
            });
            this.visibleTool(true);
            setTimeout(() => {
                this.pubSub.publish('getWidgetTableData', {
                    value: value
                });
            }, 400);
        } else {
            dispatch({
                type: 'exam/update',
                payload: {
                    refValue: value,
                    widget: false
                }
            });
            if (!exam.fromApprove) {
                if (!value.refpk) {
                    this.visibleTool(true);
                } else {
                    this.visibleTool(false);
                    button.setButtonsVisible({
                        add: true,
                        del: true,
                        search: true,
                        refresh: true,
                        commit: true, //提交
                        execute: true, //执行
                        batchAdd: true, //批量新增
                        print: true, //打印
                        recover: true, //收回
                        organization: true, //编辑情况
                        sendMsg: true, //发送通知
                        out: true, //输出
                    });
                    setTimeout(() => {
                        this.pubSub.publish('initData', {
                            pk_org: value.refpk
                        });
                    }, 400);
                }
            }
        }
    };

    /**
     * 禁用按钮方法
     */
    visibleTool = (flag) => {
        const {props} = this.comp;
        const {button} = props;
        let buttons = {
            add: flag,
            edit: flag,
            del: flag,
            search: flag,
            refresh: flag,
            commit: flag, //提交
            execute: flag, //执行
            batchAdd: flag, //批量新增
            print: flag, //打印
            recover: flag, //收回
            organization: flag, //编辑情况
            file: flag, //附件管理
            sendMsg: flag, //发送通知
            out: flag, //输出
            check_appr_opini: flag //查看审批意见
        };
        button.setButtonDisabled(buttons);
    };

    /**
     * 按钮工具
     * @param flag 传入按钮显隐锁
     */
    buttonTool = (props, flag) => {
        const {exam} = props;
        let buttonVisible = props.button.setButtonsVisible;

        let buttonAction = {
            //浏览态按钮装状态
            add: flag,
            batchAdd: flag,
            edit: false,
            del: flag,
            copy: flag,
            search: flag,
            refresh: flag,
            commit: flag, //提交
            execute: flag, //执行
            aux_function: flag, //辅助功能
            print: flag, //打印
            template_print: flag, //模板打印
            psncard: flag,
            file: exam.fromApprove ? true : false
        };

        let buttonEdit = {
            //编辑态按钮状态
            save: !flag,
            cancel: !flag
        };
        buttonVisible({
            autogen: 'head',
            ...buttonAction,
            ...buttonEdit
        });
    };

    /**
     * 取消提示框
     * @param flag 按钮状态
     */
    cancelFunction = (props, flag) => {
        promptBox({
            color: 'warning',
            title: props.exam.json['gx6008-000023'], //您确定要取消吗
            noCancelBtn: false,
            beSureBtnName: props.exam.json['gx6008-000024'], //确定
            cancelBtnName: props.exam.json['gx6008-000025'], //取消
            hasCloseBtn: false,
            beSureBtnClick: this.functionSure.bind(this, props, flag)
        });
    };

    /**
     * 确定取消
     */
    functionSure = (props, flag, flagSave) => {
        const {dispatch, button, form, exam} = props;
        this.buttonTool(props, true);

        if (!flagSave && this.comp.props.exam.fromApprove === false) {
            this.cancelAdd();
        } else {
            form.setFormStatus('card', 'browse');
        }

        button.setButtonsVisible({
            batchAdd: false,
            search: false
        });
        dispatch({
            type: 'exam/update',
            payload: {
                editState: false,
                page: ''
            }
        });

        this.comp.action.formAct.approveButton();
    };

    // 取消新增通用方法
    cancelAdd = async () => {
        const {props, action} = this.comp;
        const {dispatch, exam, form, editTable} = props;

        let postData = {
            pk_org: exam.refValue.refpk,
            formData: form.getAllFormValue('card')
        };
        try {
            let res = await dispatch({
                type: 'exam/cancelAdd',
                payload: {
                    postData: postData
                }
            });
            if (res.success) {
                form.EmptyAllFormValue('card');
                form.setFormStatus('card', 'browse');

                let data = editTable.getClickRowIndex('list');
                if (data) {
                    // 若表格有光标选中数据则显示选中行数据
                    let billid = data.record.values.pk_hi_regapply.value;
                    action.formAct.oneAction(billid);
                } else {
                    // 显示表格第一行数据
                    if (editTable.getAllRows('list').length > 0) {
                        let billid =
                            exam.billid === true
                                ? exam.billid
                                : editTable.getAllRows('list')[0].values.pk_hi_regapply.value;
                        action.formAct.oneAction(billid);
                    } else {
                        action.formAct.oneAction();
                    }
                }
            }
        } catch (e) {
        }
    };

    /**
     *
     * 单据状态改变
     */

    statesChange = async (value = []) => {
        const {props} = this.comp;
        const {dispatch} = props;
        //但据状态中包含全部且不止全部
        if (value.indexOf('all') > -1 && value.length > 1) {
            for (var i = 0; i < value.length; i++) {
                if (value[0] === 'all') {
                    value = value.splice(1, 1);
                } else {
                    value = ['all'];
                }
            }
            dispatch({
                type: 'exam/update',
                payload: {
                    billStatus: value
                }
            });

            this.pubSub.publish('initData', {
                billStatus: value
            });
        } else {
            let res = await dispatch({
                type: 'exam/update',
                payload: {
                    billStatus: value
                }
            });
            this.pubSub.publish('initData', {
                billStatus: value
            });
        }
    };

    /**
     * 时间函数
     */
    timeChange = (value) => {
        let {props} = this.comp;
        let {dispatch, exam} = props;
        dispatch({
            type: 'exam/update',
            payload: {
                time: value,
                beginTime: '',
                endTime: ''
            }
        });
        if (value !== 'custom') {
            this.pubSub.publish('initData', {
                time: value
            });
        }
    };

    beginTime = (value) => {
        let {props} = this.comp;
        let {dispatch, exam} = props;

        if (exam.endTime) {
            this.pubSub.publish('initData', {
                beginTime: value
            });
        }

        dispatch({
            type: 'exam/update',
            payload: {
                beginTime: value
            }
        });
    };
    endTime = (value) => {
        let {props} = this.comp;
        let {dispatch, exam} = props;
        if (exam.beginTime) {
            this.pubSub.publish('initData', {
                endTime: value
            });
        }

        dispatch({
            type: 'exam/update',
            payload: {
                endTime: value
            }
        });
    };

    // 展示查询弹窗
    showSearchModal = () => {
        const {props, action} = this.comp;
        const {search} = props;
        action.formAct.formBeforeEdit({}, {}, 'pk_psnjob');
        search.openAdvSearch('query', true);
    };
}
